package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.mapper.pub.PubReportRulesMapper;
import com.ysd.lis.request.*;
import com.ysd.lis.request.bac.BacRptOverviewDto;
import com.ysd.lis.request.bac.BacRptOverviewItemDto;
import com.ysd.lis.request.bac.BacRptOverviewParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.bac.*;
import com.ysd.lis.service.common.RedisSysParamHelper;
import com.ysd.lis.service.lab.*;
import com.ysd.util.IncrementalNumberGenerator;
import com.ysd.util.RedisUserManager;
import com.ysd.util.SortMappers;
import com.ysd.util.ToolsUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Cfz
 * @since 2023-12-26
 */
@Service
public class LabMaininfoBacServiceImpl extends ServiceImpl<LabMaininfoMapper, LabMaininfo> implements LabMaininfoBacService {
    private static final Logger logger = LoggerFactory.getLogger(LabMaininfoBacServiceImpl.class);

    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    BacTestResultMapper bacTestResultMapper;
    @Autowired
    BacTestResultService bacTestResultService;
    @Autowired
    BacTestCultureMediumMapper bacTestCultureMediumMapper;
    @Autowired
    BacDrugTestResultMapper bacDrugTestResultMapper;
    @Autowired
    LabRptresultImageMapper labRptresultImageMapper;
    @Autowired
    LabMainStateService labMainStateService;
    @Autowired
    LabReqStateService labReqStateService;
    @Autowired
    PubReportRulesMapper reportRulesMapper;
    @Autowired
    LabRptmainMapper labRptmainMapper;
    @Autowired
    LabRptdetailMapper labRptdetailMapper;
    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    BacStainingResultService bacStainingResultService;
    @Autowired
    BacObserResultMapper bacObserResultMapper;
    @Autowired
    BacObserResultService bacObserResultService;
    @Autowired
    LabRptdetailBacService labRptdetailBacService;
    @Autowired
    LabRptdetailStainingService labRptdetailStainingService;
    @Autowired
    LabRptdetailDrugService labRptdetailDrugService;
    @Autowired
    LabRptdetailObserService labRptdetailObserService;
    @Autowired
    PubReportMapper pubReportMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    BacDrugTestResultService bacDrugTestResultService;
    @Autowired
    BacAddFeeService bacAddFeeService;
    @Autowired
    BacStrainMapper bacStrainMapper;
    @Autowired
    BacObserResultNoGermMapper bacObserResultNoGermMapper;

    @Override
    public Result deleteMaininfoBacById(LabMaininfo labMaininfo) {
        if (ToolsUtils.isNotEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().intValue() > 0) {
            return Result.fail("已审核不允许删除！");
        }

        int i = labMaininfoMapper.deleteById(labMaininfo.getId());

        Timestamp timestamp = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");

        Timestamp timestamp1 = new Timestamp(labMaininfo.getSampleda().getTime());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate1 = sdf1.format(timestamp1);
        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");

        /*
        select * from BAC_TEST_FLOW  where SAMPLE_NO = '241127004'
         */
        LambdaQueryWrapper<BacTestWorkFlow> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(BacTestWorkFlow::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper1.eq(BacTestWorkFlow::getSampleNo, labMaininfo.getSampleNo());

        lambdaQueryWrapper1.ge(BacTestWorkFlow::getSampleda, startTime);
        lambdaQueryWrapper1.le(BacTestWorkFlow::getSampleda, endTime);
        bacTestWorkFlowMapper.delete(lambdaQueryWrapper1);

         /*
        select * from BAC_TEST_FLOW_NODE  where SAMPLE_NO = '241127004'
         */
        LambdaQueryWrapper<BacTestWorkFlowNode> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper3.eq(BacTestWorkFlowNode::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper3.eq(BacTestWorkFlowNode::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper3.ge(BacTestWorkFlowNode::getSampleda, startTime);
        lambdaQueryWrapper3.le(BacTestWorkFlowNode::getSampleda, endTime);
        bacTestWorkFlowNodeMapper.delete(lambdaQueryWrapper3);

//        select * from BAC_RPTRESULT   where SAMPLE_NO = '241127004';

        LambdaQueryWrapper<BacTestResult> lambdaQueryWrapper4 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper4.eq(BacTestResult::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper4.eq(BacTestResult::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper4.ge(BacTestResult::getSampleda, startTime);
        lambdaQueryWrapper4.le(BacTestResult::getSampleda, endTime);
        bacTestResultMapper.delete(lambdaQueryWrapper4);

        //删除选用培养基
        LambdaQueryWrapper<BacTestCultureMedium> lambdaQueryWrapperPYJ = new LambdaQueryWrapper<>();
        lambdaQueryWrapperPYJ.eq(BacTestCultureMedium::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapperPYJ.eq(BacTestCultureMedium::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapperPYJ.ge(BacTestCultureMedium::getSampleda, startTime);
        lambdaQueryWrapperPYJ.le(BacTestCultureMedium::getSampleda, endTime);
        bacTestCultureMediumMapper.delete(lambdaQueryWrapperPYJ);

//        select * from BAC_DRUG_RESULT   where SAMPLE_NO = '241127004';
        LambdaQueryWrapper<BacDrugTestResult> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper5.eq(BacDrugTestResult::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper5.eq(BacDrugTestResult::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper5.ge(BacDrugTestResult::getSampleda, startTime);
        lambdaQueryWrapper5.le(BacDrugTestResult::getSampleda, endTime);
        bacDrugTestResultMapper.delete(lambdaQueryWrapper5);

        //BAC_BLOOD_CULTRUE
        LambdaQueryWrapper<BacBloodCultrue> lambdaQueryWrapper6 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper6.eq(BacBloodCultrue::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper6.eq(BacBloodCultrue::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper6.ge(BacBloodCultrue::getSampleda, startTime);
        lambdaQueryWrapper6.le(BacBloodCultrue::getSampleda, endTime);
        bacBloodCultrueMapper.delete(lambdaQueryWrapper6);
        //BAC_OBSER_RESULT
        LambdaQueryWrapper<BacObserResult> lambdaQueryWrapper7 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper7.eq(BacObserResult::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper7.eq(BacObserResult::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper7.ge(BacObserResult::getSampleda, startTime);
        lambdaQueryWrapper7.le(BacObserResult::getSampleda, endTime);
        bacObserResultMapper.delete(lambdaQueryWrapper7);

        //BAC_STRAIN
        //菌株
        LambdaQueryWrapper<BacStrain> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(BacStrain::getRptGroup, labMaininfo.getRptGroup());
        queryWrapper1.eq(BacStrain::getSampleNo, labMaininfo.getSampleNo());
        queryWrapper1.ge(BacStrain::getSampleda, startTime);
        queryWrapper1.le(BacStrain::getSampleda, endTime);
        bacStrainMapper.delete(queryWrapper1);

        //BAC_STAINING_RESULT
        LambdaQueryWrapper<BacStainingResult> lambdaQueryWrapper8 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper8.eq(BacStainingResult::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper8.eq(BacStainingResult::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper8.ge(BacStainingResult::getSampleda, startTime);
        lambdaQueryWrapper8.le(BacStainingResult::getSampleda, endTime);
        bacStainingResultMapper.delete(lambdaQueryWrapper8);

        LambdaQueryWrapper<BacObserResultNoGerm> lambdaQueryWrapper9 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper9.eq(BacObserResultNoGerm::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper9.eq(BacObserResultNoGerm::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper9.ge(BacObserResultNoGerm::getSampleda, startTime);
        lambdaQueryWrapper9.le(BacObserResultNoGerm::getSampleda, endTime);
        bacObserResultNoGermMapper.delete(lambdaQueryWrapper9);

        //删除图片
        LambdaQueryWrapper<LabRptresultImage> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(LabRptresultImage::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper2.eq(LabRptresultImage::getSampleNo, labMaininfo.getSampleNo());
        lambdaQueryWrapper2.ge(LabRptresultImage::getSampleda, startTime);
        lambdaQueryWrapper2.le(LabRptresultImage::getSampleda, endTime);
        labRptresultImageMapper.delete(lambdaQueryWrapper2);


        try {
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                LabMainState reqState1 = new LabMainState();
                reqState1.setMaininfoId(labMaininfo.getId());
                reqState1.setStateCode("9000");
                reqState1.setStateValue("删除上机记录");
                reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】" + "由" + sysUser.getRealname() + "删除上机记录");
                labMainStateService.save(reqState1);
            }).start();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (i > 0) {
            return Result.succ(1, "删除数据成功", "");
        } else {
            return Result.fail("删除数据失败！");
        }
    }

    @Override
    public Result LabMainInfoBatchDelete(LabMainInfoBatchDelete input) {
        if (BeanUtil.isEmpty(input.getSampleda())) {
            return Result.fail("检验日期为空");
        }
        if (BeanUtil.isEmpty(input.getRptGroup())) {
            return Result.fail("报告单元为空");
        }
        if (input.getRange().isEmpty()) {
            return Result.fail("标本号范围为空");
        }
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.eq(LabMaininfo::getRptGroup, input.getRptGroup());

        Timestamp startTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getSampleda().substring(0, 10) + " 23:59:59");
        queryWrapper.ge(LabMaininfo::getSampleda, startTime);
        queryWrapper.le(LabMaininfo::getSampleda, endTime);

        List<SampleNoRange> rangeList = input.getRange();

        Integer i = 0;
        for (SampleNoRange itm : rangeList) {
            if (BeanUtil.isEmpty(itm.getS()) || BeanUtil.isEmpty(itm.getE())) {
                return Result.fail((i + 1) + "行,开始号段或结束号段不允许为空");
            }
            i++;
        }

        List<String> sampleNoList = getSampleNoList(rangeList.get(0));
        queryWrapper.in(LabMaininfo::getSampleNo, sampleNoList);
        List<LabMaininfo> list = labMaininfoMapper.selectList(queryWrapper);

        sortLabMainInfo(list);

        List<Predicate<LabMaininfo>> dynamicPredicates = new ArrayList<>();

        for (SampleNoRange itm : input.getRange()) {
            dynamicPredicates.add(p -> p.getSeqNo() >= replaceLetter(itm.getS()) && p.getSeqNo() <= replaceLetter(itm.getE()));
        }

        List<LabMaininfo> list1 = list.stream().filter(t -> dynamicPredicates.stream().anyMatch(p -> p.test(t))).collect(Collectors.toList());

        if (list1.isEmpty()) {
            return Result.succ(1, "没有要删除的项", null);
        }

        List<LabMaininfo> listChk1 = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsChk()) && (p.getIsChk().compareTo(new BigDecimal(1)) == 0 || p.getIsChk().compareTo(new BigDecimal(2)) == 0)).collect(Collectors.toList());

        if (!listChk1.isEmpty()) {
            return Result.fail("号段中存在已初审或已审核的数据");
        }

        List<LabMaininfo> listLock = list1.stream().filter(p -> !BeanUtil.isEmpty(p.getIsLock()) && p.getIsLock().equals(1)).collect(Collectors.toList());

        if (!listLock.isEmpty()) {
            return Result.fail("号段中存在已锁定的数据");
        }

        for (LabMaininfo labMaininfo : list1){

            //删除方案
            LambdaQueryWrapper<BacTestWorkFlow> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(BacTestWorkFlow::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper1.eq(BacTestWorkFlow::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper1.ge(BacTestWorkFlow::getSampleda, startTime);
            lambdaQueryWrapper1.le(BacTestWorkFlow::getSampleda, endTime);
            bacTestWorkFlowMapper.delete(lambdaQueryWrapper1);

         /*
        select * from BAC_TEST_FLOW_NODE  where SAMPLE_NO = '241127004'
         */
            //删除节点
            LambdaQueryWrapper<BacTestWorkFlowNode> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper3.eq(BacTestWorkFlowNode::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper3.eq(BacTestWorkFlowNode::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper3.ge(BacTestWorkFlowNode::getSampleda, startTime);
            lambdaQueryWrapper3.le(BacTestWorkFlowNode::getSampleda, endTime);
            bacTestWorkFlowNodeMapper.delete(lambdaQueryWrapper3);

//        select * from BAC_RPTRESULT   where SAMPLE_NO = '241127004';
            //微生物结果
            LambdaQueryWrapper<BacTestResult> lambdaQueryWrapper4 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper4.eq(BacTestResult::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper4.eq(BacTestResult::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper4.ge(BacTestResult::getSampleda, startTime);
            lambdaQueryWrapper4.le(BacTestResult::getSampleda, endTime);
            bacTestResultMapper.delete(lambdaQueryWrapper4);

            //删除选用培养基
            LambdaQueryWrapper<BacTestCultureMedium> lambdaQueryWrapperPYJ = new LambdaQueryWrapper<>();
            lambdaQueryWrapperPYJ.eq(BacTestCultureMedium::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapperPYJ.eq(BacTestCultureMedium::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapperPYJ.ge(BacTestCultureMedium::getSampleda, startTime);
            lambdaQueryWrapperPYJ.le(BacTestCultureMedium::getSampleda, endTime);
            bacTestCultureMediumMapper.delete(lambdaQueryWrapperPYJ);

//        select * from BAC_DRUG_RESULT   where SAMPLE_NO = '241127004';
            //药敏结果
            LambdaQueryWrapper<BacDrugTestResult> lambdaQueryWrapper5 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper5.eq(BacDrugTestResult::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper5.eq(BacDrugTestResult::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper5.ge(BacDrugTestResult::getSampleda, startTime);
            lambdaQueryWrapper5.le(BacDrugTestResult::getSampleda, endTime);
            bacDrugTestResultMapper.delete(lambdaQueryWrapper5);

            //BAC_BLOOD_CULTRUE
            //血培养结果
            LambdaQueryWrapper<BacBloodCultrue> lambdaQueryWrapper6 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper6.eq(BacBloodCultrue::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper6.eq(BacBloodCultrue::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper6.ge(BacBloodCultrue::getSampleda, startTime);
            lambdaQueryWrapper6.le(BacBloodCultrue::getSampleda, endTime);
            bacBloodCultrueMapper.delete(lambdaQueryWrapper6);
            //BAC_OBSER_RESULT
            //菌落观察结果
            LambdaQueryWrapper<BacObserResult> lambdaQueryWrapper7 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper7.eq(BacObserResult::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper7.eq(BacObserResult::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper7.ge(BacObserResult::getSampleda, startTime);
            lambdaQueryWrapper7.le(BacObserResult::getSampleda, endTime);
            bacObserResultMapper.delete(lambdaQueryWrapper7);

            //BAC_STRAIN
            //菌株
            LambdaQueryWrapper<BacStrain> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(BacStrain::getRptGroup, labMaininfo.getRptGroup());
            queryWrapper1.eq(BacStrain::getSampleNo, labMaininfo.getSampleNo());
            queryWrapper1.ge(BacStrain::getSampleda, startTime);
            queryWrapper1.le(BacStrain::getSampleda, endTime);
            bacStrainMapper.delete(queryWrapper1);

            //BAC_STAINING_RESULT
            //染色结果
            LambdaQueryWrapper<BacStainingResult> lambdaQueryWrapper8 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper8.eq(BacStainingResult::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper8.eq(BacStainingResult::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper8.ge(BacStainingResult::getSampleda, startTime);
            lambdaQueryWrapper8.le(BacStainingResult::getSampleda, endTime);
            bacStainingResultMapper.delete(lambdaQueryWrapper8);

            //BAC_OBSER_RESULT_NO_GERM
            //培养观察结果-无菌
            LambdaQueryWrapper<BacObserResultNoGerm> lambdaQueryWrapper9 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper9.eq(BacObserResultNoGerm::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper9.eq(BacObserResultNoGerm::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper9.ge(BacObserResultNoGerm::getSampleda, startTime);
            lambdaQueryWrapper9.le(BacObserResultNoGerm::getSampleda, endTime);
            bacObserResultNoGermMapper.delete(lambdaQueryWrapper9);

            //删除图片
            LambdaQueryWrapper<LabRptresultImage> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(LabRptresultImage::getRptGroup, labMaininfo.getRptGroup());
            lambdaQueryWrapper2.eq(LabRptresultImage::getSampleNo, labMaininfo.getSampleNo());
            lambdaQueryWrapper2.ge(LabRptresultImage::getSampleda, startTime);
            lambdaQueryWrapper2.le(LabRptresultImage::getSampleda, endTime);
            labRptresultImageMapper.delete(lambdaQueryWrapper2);

            try {
                SysUser sysUser = RedisUserManager.getUser();
                new Thread(() -> {
                    LabMainState reqState1 = new LabMainState();
                    reqState1.setMaininfoId(labMaininfo.getId());
                    reqState1.setStateCode("9000");
                    reqState1.setStateValue("删除上机记录");
                    reqState1.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】" + "由" + sysUser.getRealname() + "删除上机记录");
                    labMainStateService.save(reqState1);
                }).start();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        List<String> mIds = list1.stream().map(LabMaininfo::getId).collect(Collectors.toList());
        int i1 = labMaininfoMapper.deleteBatchIds(mIds);
        if (i1 > 0){
            return Result.succ("批量删除成功");
        }else{
            return Result.fail("批量删除失败");
        }
    }

    @Override
    public Result cancelReqMainAndDetail(LabMaininfo byId) {
        //改reqmain的STATE为70（标本签收）
        //更新数据
        LambdaUpdateWrapper<LabReqMain> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(LabReqMain::getState, "70").set(LabReqMain::getStateNa, "标本签收").eq(LabReqMain::getReqNo, byId.getReqNo()).eq(LabReqMain::getOrgId, byId.getOrgId()).eq(LabReqMain::getDelFlag, 0);

        int update = labReqMainMapper.update(null, lambdaUpdateWrapper);
        if (update > 0) {
            SysUser sysUser = RedisUserManager.getUser();

            //添加状态记录
            LabReqState reqState = new LabReqState();
            reqState.setReqNo(byId.getReqNo());
            reqState.setOrgId(byId.getOrgId());
            reqState.setCreator(sysUser.getId());
            reqState.setStateCode("70");
            reqState.setStateValue("标本签收");
            String rmk = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "取消上机,标本号:" + byId.getReqNo();
            reqState.setRemark(rmk);
            reqState.setSeq(labReqStateService.getMaxCount(byId.getReqNo()));
            labReqStateService.save(reqState);
        }

        return Result.succ(1, "修改数据成功", "");
    }

    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;

    @Override
    public Result findMainInfoById(LabMaininfo labMaininfo) {
        return Result.succ(1, "查询成功", labMainInfoServiceBak.getMainInfoById(labMaininfo.getId()));
    }

    //    @Transactional(rollbackFor = Exception.class)
    public Result previewBacRpt(LabMaininfo labMaininfo) throws JsonProcessingException {
        if (ToolsUtils.isEmpty(labMaininfo)) {
            return Result.fail("入参异常！");
        }
        //根据报告单元获取模版codeR
//        MPJLambdaWrapper<PubReportRules> reportRulesWrapper = new MPJLambdaWrapper<>();
//        reportRulesWrapper.selectAll(PubReportRules.class).selectAs(PubReport::getName, PubReportRules::getReportName).leftJoin(PubReport.class, PubReport::getCode, PubReportRules::getReportCode).eq(PubReportRules::getDelFlag, 0).eq(PubReportRules::getRptGroup, labMaininfo.getRptGroup()).orderByAsc(PubReportRules::getRuleType);
//
//        List<PubReportRules> reportRules = reportRulesMapper.selectList(reportRulesWrapper);
//        if (ToolsUtils.isEmpty(reportRules) || reportRules.size() == 0) {
//            return Result.fail("根据报告单元未获取到报告模版！");
//        }

        int i = 0;
        String mainInfoId = labMaininfo.getId();//检验记录主键
        LambdaQueryWrapper<LabRptmain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabRptmain::getDelFlag, 0);
        queryWrapper.eq(LabRptmain::getMainInfoId, mainInfoId);
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            queryWrapper.eq(LabRptmain::getOrgId, sysUser.getOrgId());
        }
        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(labRptmainList)) {
            for (LabRptmain labRptmain : labRptmainList) {
                LambdaQueryWrapper<LabRptdetail> delLabRptdetailWrapper = new LambdaQueryWrapper<>();
                delLabRptdetailWrapper.eq(LabRptdetail::getRptMainCode, labRptmain.getRptCode());
                labRptdetailMapper.delete(delLabRptdetailWrapper);
                labRptmainMapper.deleteById(labRptmain.getId());
            }
        }

        //血培养
        LambdaQueryWrapper<BacBloodCultrue> bloodWrapper = new LambdaQueryWrapper<>();
        bloodWrapper.eq(BacBloodCultrue::getDelFlag, 0).eq(BacBloodCultrue::getSampleda, labMaininfo.getSampleda()).eq(BacBloodCultrue::getSampleNo, labMaininfo.getSampleNo()).eq(BacBloodCultrue::getRptGroup, labMaininfo.getRptGroup());
        List<BacBloodCultrue> bacBloodCultrues = bacBloodCultrueMapper.selectList(bloodWrapper);
        if(CollectionUtil.isNotEmpty(bacBloodCultrues)){
            for (BacBloodCultrue bacBloodCultrue : bacBloodCultrues) {
                bacBloodCultrue.setBacPublishStatus(BigDecimal.valueOf(1));
            }
            bacBloodCultrueService.updateBatchById(bacBloodCultrues);
        }
        //细菌检测结果
        LambdaQueryWrapper<BacTestResult> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(BacTestResult::getDelFlag, 0).eq(BacTestResult::getSampleda, labMaininfo.getSampleda()).eq(BacTestResult::getSampleNo, labMaininfo.getSampleNo()).eq(BacTestResult::getRptGroup, labMaininfo.getRptGroup());
        List<BacTestResult> bacTestResultList = bacTestResultMapper.selectList(wrapper1);
        if(CollectionUtil.isNotEmpty(bacTestResultList)){
            for (BacTestResult bacTestResult : bacTestResultList) {
                bacTestResult.setBacPublishStatus(BigDecimal.valueOf(1));
            }
            bacTestResultService.updateBatchById(bacTestResultList);
        }


        //染色结果
        LambdaQueryWrapper<BacStainingResult> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(BacStainingResult::getDelFlag, 0);
        //wrapper2.eq(BacStainingResult::getMaininfoId, labMaininfo.getId());
        wrapper2.eq(BacStainingResult::getRptGroup, labMaininfo.getRptGroup());
        wrapper2.eq(BacStainingResult::getSampleda, labMaininfo.getSampleda());
        wrapper2.eq(BacStainingResult::getSampleNo, labMaininfo.getSampleNo());

        List<BacStainingResult> bacStainingResultList = bacStainingResultMapper.selectList(wrapper2);
        if(CollectionUtil.isNotEmpty(bacStainingResultList)){
            for (BacStainingResult bacStainingResult : bacStainingResultList) {
                bacStainingResult.setIsPushSecReport(1);
            }
            bacStainingResultService.updateBatchById(bacStainingResultList);
        }
        //细菌药敏结果
        LambdaQueryWrapper<BacDrugTestResult> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(BacDrugTestResult::getDelFlag, 0)
                //  .eq(BacDrugTestResult::getMaininfoId, labMaininfo.getId());
                .eq(BacDrugTestResult::getSampleda, labMaininfo.getSampleda()).eq(BacDrugTestResult::getSampleNo, labMaininfo.getSampleNo()).eq(BacDrugTestResult::getRptGroup, labMaininfo.getRptGroup());
        List<BacDrugTestResult> bacDrugTestResultList = bacDrugTestResultMapper.selectList(wrapper3);
        //细菌药敏结果
        LambdaQueryWrapper<BacObserResult> wrapper4 = new LambdaQueryWrapper<>();
        wrapper4.eq(BacObserResult::getDelFlag, 0);
        wrapper4.and(p -> p.eq(BacObserResult::getRptGroup, labMaininfo.getRptGroup()).eq(BacObserResult::getSampleda, labMaininfo.getSampleda()).eq(BacObserResult::getSampleNo, labMaininfo.getSampleNo()));
        List<BacObserResult> bacObserResultList = bacObserResultMapper.selectList(wrapper4);
        if(CollectionUtil.isNotEmpty(bacObserResultList)){
            for (BacObserResult bacObserResult : bacObserResultList) {
                bacObserResult.setBacPublishStatus(BigDecimal.valueOf(1));
            }
            bacObserResultService.updateBatchById(bacObserResultList);
        }
//        String ruleType = reportRules.get(reportRules.size() - 1).getRuleType();


        List<ReportPreviewDto> reportPreviewDtos = new ArrayList<>();
        ReportPreviewDto reportPreviewDto;
        //LabRptmain labRptmain;

        /*计算使用哪个模板*/
        /*计算使用的模板Id,模板名称*/
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return Result.fail("未找到相关字典数据");
        }
        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("wswwymjgsfywjgmb");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        Boolean isWswwymjgsfywjgmb = false;
        if (!r1.isEmpty()) {
            if ("1".equals(r1.get(0).getValue())) {
                isWswwymjgsfywjgmb=true;
            }
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();
        //004   药敏报告  008细菌阳性无药敏结果 (有药敏结果用004,没有用008)
        String reportCode="";
        if (CollectionUtils.isEmpty(bacDrugTestResultList) && isWswwymjgsfywjgmb){
            reportCode="008";
        }else {
            reportCode="004";
        }
        String finalReportCode = reportCode;
        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && (finalReportCode.equals(map.get("pointsCode")))).collect(Collectors.toList());//阴性报告
        if (ToolsUtils.isEmpty(filteredList)) {
            return Result.fail("未找到相关字典数据");
        }
        String pointId = filteredList.get(0).get("commonId").toString();
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        pubRptQuery.eq(PubReport::getIsUse, 1);

        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return Result.fail("未找到药敏报告相关模板数据");
        }
        PubReport pubReportYM = pubReportList.get(0);
        //003   阴性报告
        List<Map<String, Object>> filteredList2 = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && ("003".equals(map.get("pointsCode")))).collect(Collectors.toList());//阴性报告
        if (ToolsUtils.isEmpty(filteredList2)) {
            return Result.fail("未找到相关字典数据");
        }
        String pointId2 = filteredList2.get(0).get("commonId").toString();
        LambdaQueryWrapper<PubReport> pubRptQuery2 = new LambdaQueryWrapper();
        pubRptQuery2.eq(PubReport::getDelFlag, 0);
        pubRptQuery2.eq(PubReport::getPointsId, pointId2);
        pubRptQuery2.eq(PubReport::getIsUse, 1);

        List<PubReport> pubReportList2 = pubReportMapper.selectList(pubRptQuery2);
        if (ToolsUtils.isEmpty(pubReportList2)) {
            return Result.fail("未找到阴性报告相关模板数据");
        }
        PubReport pubReportYX = pubReportList2.get(0);

        List<BacTestResult> YMBGList = bacTestResultList.stream().filter(p -> ToolsUtils.isNotEmpty(p.getGermNo())).collect(Collectors.toList());

        List<BacTestResult> YXBGList = bacTestResultList.stream().filter(p -> ToolsUtils.isEmpty(p.getGermNo())).collect(Collectors.toList());

        List<LabRptmain> labRptmainYMs = new ArrayList<>();
        List<LabRptmain> labRptmainYXs = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(YMBGList) && YMBGList.size() > 0) {
            /*报告单元系统选项，微生物药敏报告是否拆分报告*/
            /*报告单元系统选项，微生物药敏报告是否拆分报告 wswymbgsfhbbg*/
            String wswymbgsfhbbg = "";
            try {
                SysParamSearchOutputDto paramResult = redisSysParamHelper.getValueByBGDYXTXXCSParam(labMaininfo.getOrgId(), "wswymbgsfhbbg", labMaininfo.getRptGroup(), null);
                wswymbgsfhbbg = paramResult.getValueStr();
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (ToolsUtils.isNotEmpty(wswymbgsfhbbg) && "1".equals(wswymbgsfhbbg)) {
                for (BacTestResult tt : YMBGList) {
                    //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                    LabRptmain labRptmain = new LabRptmain();
                    labRptmain.setOrgId(sysUser.getOrgId());
                    labRptmain.setMainInfoId(tt.getId());
                    labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                    labRptmain.setSampleda(labMaininfo.getSampleda());
                    labRptmain.setSampleNo(labMaininfo.getSampleNo());
                    labRptmain.setRptGroup(labMaininfo.getRptGroup());
                    labRptmain.setRptTemplateCode(pubReportYM.getId());//reportRules.get(reportRules.size() - 1).getReportId());
                    labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                    labRptmain.setPublishDoctorNa(sysUser.getRealname());
                    labRptmain.setIsExported(0);
                    labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                    i = labRptmainMapper.insert(labRptmain);
                    if (i > 0) {
                        labRptmainYMs.add(labRptmain);
                        if (ToolsUtils.isNotEmpty(bacTestResultList)) {
                            List<LabRptdetailBac> labRptdetailBacList = new ArrayList<>();
                            for (BacTestResult bacTestResult : bacTestResultList) {
                                LabRptdetailBac labRptdetailBac = new LabRptdetailBac();
                                labRptdetailBac.setOrgId(sysUser.getOrgId());
                                labRptdetailBac.setRptMainCode(labRptmain.getRptCode());
                                labRptdetailBac.setRptMainId(labRptmain.getId());
                                labRptdetailBac.setBacTestResultId(bacTestResult.getId());
                                labRptdetailBacList.add(labRptdetailBac);
                            }
                            if (ToolsUtils.isNotEmpty(labRptdetailBacList)) {
                                labRptdetailBacService.saveBatch(labRptdetailBacList);
                            }
                        }

                        if (ToolsUtils.isNotEmpty(bacStainingResultList)) {
                            List<LabRptdetailStaining> labRptdetailStainingList = new ArrayList<>();
                            for (BacStainingResult bacStainingResult : bacStainingResultList) {
                                LabRptdetailStaining labRptdetailStaining = new LabRptdetailStaining();
                                labRptdetailStaining.setOrgId(sysUser.getOrgId());
                                labRptdetailStaining.setRptMainCode(labRptmain.getRptCode());
                                labRptdetailStaining.setRptMainId(labRptmain.getId());
                                labRptdetailStaining.setBacStainingResultId(bacStainingResult.getId());
                                labRptdetailStainingList.add(labRptdetailStaining);
                            }
                            if (ToolsUtils.isNotEmpty(labRptdetailStainingList)) {
                                labRptdetailStainingService.saveBatch(labRptdetailStainingList);
                            }
                        }

                        if (ToolsUtils.isNotEmpty(bacDrugTestResultList)) {
                            List<LabRptdetailDrug> labRptdetailDrugList = new ArrayList<>();
                            for (BacDrugTestResult bacDrugTestResult : bacDrugTestResultList) {
                                LabRptdetailDrug labRptdetailDrug = new LabRptdetailDrug();
                                labRptdetailDrug.setOrgId(sysUser.getOrgId());
                                labRptdetailDrug.setRptMainCode(labRptmain.getRptCode());
                                labRptdetailDrug.setRptMainId(labRptmain.getId());
                                labRptdetailDrug.setBacDrugResultId(bacDrugTestResult.getId());
                                labRptdetailDrugList.add(labRptdetailDrug);
                            }
                            if (ToolsUtils.isNotEmpty(labRptdetailDrugList)) {
                                labRptdetailDrugService.saveBatch(labRptdetailDrugList);
                            }
                        }
                        if (ToolsUtils.isNotEmpty(bacObserResultList)) {
                            List<LabRptdetailObser> labRptdetailObserList = new ArrayList<>();
                            for (BacObserResult bacObserResult : bacObserResultList) {
                                LabRptdetailObser labRptdetailObser = new LabRptdetailObser();
                                labRptdetailObser.setOrgId(sysUser.getOrgId());
                                labRptdetailObser.setRptMainCode(labRptmain.getRptCode());
                                labRptdetailObser.setRptMainId(labRptmain.getId());
                                labRptdetailObser.setBacObserResultId(bacObserResult.getId());
                                labRptdetailObserList.add(labRptdetailObser);
                            }
                            if (ToolsUtils.isNotEmpty(labRptdetailObserList)) {
                                boolean b = labRptdetailObserService.saveBatch(labRptdetailObserList);
                            }
                        }
                    }
                }
            } else {
                BacTestResult tt = YMBGList.get(0);
                //插入LAB_RPTMAIN 与 LAB_RPTDETAIL表信息
                LabRptmain labRptmain = new LabRptmain();
                labRptmain.setOrgId(sysUser.getOrgId());
                labRptmain.setMainInfoId(ToolsUtils.isNotEmpty(tt) ? tt.getId() : "");
                labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
                labRptmain.setRptGroup(labMaininfo.getRptGroup());
                labRptmain.setSampleda(labMaininfo.getSampleda());
                labRptmain.setSampleNo(labMaininfo.getSampleNo());
                labRptmain.setRptGroup(labMaininfo.getRptGroup());
                labRptmain.setRptTemplateCode(pubReportYM.getId());//reportRules.get(reportRules.size() - 1).getReportId());
                labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
                labRptmain.setPublishDoctorNa(sysUser.getRealname());
                labRptmain.setIsExported(0);
                labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
                i = labRptmainMapper.insert(labRptmain);
                if (i > 0) {
                    labRptmainYMs.add(labRptmain);
                    if (ToolsUtils.isNotEmpty(bacTestResultList)) {
                        List<LabRptdetailBac> labRptdetailBacList = new ArrayList<>();
                        for (BacTestResult bacTestResult : bacTestResultList) {
                            LabRptdetailBac labRptdetailBac = new LabRptdetailBac();
                            labRptdetailBac.setOrgId(sysUser.getOrgId());
                            labRptdetailBac.setRptMainCode(labRptmain.getRptCode());
                            labRptdetailBac.setRptMainId(labRptmain.getId());
                            labRptdetailBac.setBacTestResultId(bacTestResult.getId());
                            labRptdetailBacList.add(labRptdetailBac);
                        }
                        if (ToolsUtils.isNotEmpty(labRptdetailBacList)) {
                            labRptdetailBacService.saveBatch(labRptdetailBacList);
                        }
                    }

                    if (ToolsUtils.isNotEmpty(bacStainingResultList)) {
                        List<LabRptdetailStaining> labRptdetailStainingList = new ArrayList<>();
                        for (BacStainingResult bacStainingResult : bacStainingResultList) {
                            LabRptdetailStaining labRptdetailStaining = new LabRptdetailStaining();
                            labRptdetailStaining.setOrgId(sysUser.getOrgId());
                            labRptdetailStaining.setRptMainCode(labRptmain.getRptCode());
                            labRptdetailStaining.setRptMainId(labRptmain.getId());
                            labRptdetailStaining.setBacStainingResultId(bacStainingResult.getId());
                            labRptdetailStainingList.add(labRptdetailStaining);
                        }
                        if (ToolsUtils.isNotEmpty(labRptdetailStainingList)) {
                            labRptdetailStainingService.saveBatch(labRptdetailStainingList);
                        }
                    }

                    if (ToolsUtils.isNotEmpty(bacDrugTestResultList)) {
                        List<LabRptdetailDrug> labRptdetailDrugList = new ArrayList<>();
                        for (BacDrugTestResult bacDrugTestResult : bacDrugTestResultList) {
                            LabRptdetailDrug labRptdetailDrug = new LabRptdetailDrug();
                            labRptdetailDrug.setOrgId(sysUser.getOrgId());
                            labRptdetailDrug.setRptMainCode(labRptmain.getRptCode());
                            labRptdetailDrug.setRptMainId(labRptmain.getId());
                            labRptdetailDrug.setBacDrugResultId(bacDrugTestResult.getId());
                            labRptdetailDrugList.add(labRptdetailDrug);
                        }
                        if (ToolsUtils.isNotEmpty(labRptdetailDrugList)) {
                            labRptdetailDrugService.saveBatch(labRptdetailDrugList);
                        }
                    }
                    if (ToolsUtils.isNotEmpty(bacObserResultList)) {
                        List<LabRptdetailObser> labRptdetailObserList = new ArrayList<>();
                        for (BacObserResult bacObserResult : bacObserResultList) {
                            LabRptdetailObser labRptdetailObser = new LabRptdetailObser();
                            labRptdetailObser.setOrgId(sysUser.getOrgId());
                            labRptdetailObser.setRptMainCode(labRptmain.getRptCode());
                            labRptdetailObser.setRptMainId(labRptmain.getId());
                            labRptdetailObser.setBacObserResultId(bacObserResult.getId());
                            labRptdetailObserList.add(labRptdetailObser);
                        }
                        if (ToolsUtils.isNotEmpty(labRptdetailObserList)) {
                            boolean b = labRptdetailObserService.saveBatch(labRptdetailObserList);
                        }
                    }
                }
            }
        }
        if (ToolsUtils.isNotEmpty(YXBGList) && YXBGList.size() > 0) {
            //String  YXBGList.stream().map(p->p.getGermNa()).collect(Collectors.joining(","));
            LabRptmain labRptmain = new LabRptmain();
            labRptmain.setOrgId(sysUser.getOrgId());
            labRptmain.setMainInfoId(labMaininfo.getId());
            labRptmain.setRptCode(IncrementalNumberGenerator.generateIncrementalNumber4());
            labRptmain.setRptGroup(labMaininfo.getRptGroup());
            labRptmain.setSampleda(labMaininfo.getSampleda());
            labRptmain.setSampleNo(labMaininfo.getSampleNo());
            labRptmain.setRptGroup(labMaininfo.getRptGroup());
            labRptmain.setRptTemplateCode(pubReportYX.getId());//reportRules.get(reportRules.size() - 1).getReportId());
            labRptmain.setPublishDoctor(sysUser.getHisEmployeeCode());
            labRptmain.setPublishDoctorNa(sysUser.getRealname());
            labRptmain.setIsExported(0);
            labRptmain.setIsFinalReport(!BeanUtil.isEmpty(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal((2))) ? 1 : 0);
            i = labRptmainMapper.insert(labRptmain);

            if (i > 0) {
                labRptmainYXs.add(labRptmain);
                if (ToolsUtils.isNotEmpty(bacTestResultList)) {
                    List<LabRptdetailBac> labRptdetailBacList = new ArrayList<>();
                    for (BacTestResult bacTestResult : bacTestResultList) {
                        LabRptdetailBac labRptdetailBac = new LabRptdetailBac();
                        labRptdetailBac.setOrgId(sysUser.getOrgId());
                        labRptdetailBac.setRptMainCode(labRptmain.getRptCode());
                        labRptdetailBac.setRptMainId(labRptmain.getId());
                        labRptdetailBac.setBacTestResultId(bacTestResult.getId());
                        labRptdetailBacList.add(labRptdetailBac);
                    }
                    if (ToolsUtils.isNotEmpty(labRptdetailBacList)) {
                        labRptdetailBacService.saveBatch(labRptdetailBacList);
                    }
                }

                if (ToolsUtils.isNotEmpty(bacStainingResultList)) {
                    List<LabRptdetailStaining> labRptdetailStainingList = new ArrayList<>();
                    for (BacStainingResult bacStainingResult : bacStainingResultList) {
                        LabRptdetailStaining labRptdetailStaining = new LabRptdetailStaining();
                        labRptdetailStaining.setOrgId(sysUser.getOrgId());
                        labRptdetailStaining.setRptMainCode(labRptmain.getRptCode());
                        labRptdetailStaining.setRptMainId(labRptmain.getId());
                        labRptdetailStaining.setBacStainingResultId(bacStainingResult.getId());
                        labRptdetailStainingList.add(labRptdetailStaining);
                    }
                    if (ToolsUtils.isNotEmpty(labRptdetailStainingList)) {
                        labRptdetailStainingService.saveBatch(labRptdetailStainingList);
                    }
                }

                if (ToolsUtils.isNotEmpty(bacDrugTestResultList)) {
                    List<LabRptdetailDrug> labRptdetailDrugList = new ArrayList<>();
                    for (BacDrugTestResult bacDrugTestResult : bacDrugTestResultList) {
                        LabRptdetailDrug labRptdetailDrug = new LabRptdetailDrug();
                        labRptdetailDrug.setOrgId(sysUser.getOrgId());
                        labRptdetailDrug.setRptMainCode(labRptmain.getRptCode());
                        labRptdetailDrug.setRptMainId(labRptmain.getId());
                        labRptdetailDrug.setBacDrugResultId(bacDrugTestResult.getId());
                        labRptdetailDrugList.add(labRptdetailDrug);
                    }
                    if (ToolsUtils.isNotEmpty(labRptdetailDrugList)) {
                        labRptdetailDrugService.saveBatch(labRptdetailDrugList);
                    }
                }
                if (ToolsUtils.isNotEmpty(bacObserResultList)) {
                    List<LabRptdetailObser> labRptdetailObserList = new ArrayList<>();
                    for (BacObserResult bacObserResult : bacObserResultList) {
                        LabRptdetailObser labRptdetailObser = new LabRptdetailObser();
                        labRptdetailObser.setOrgId(sysUser.getOrgId());
                        labRptdetailObser.setRptMainCode(labRptmain.getRptCode());
                        labRptdetailObser.setRptMainId(labRptmain.getId());
                        labRptdetailObser.setBacObserResultId(bacObserResult.getId());
                        labRptdetailObserList.add(labRptdetailObser);
                    }
                    if (ToolsUtils.isNotEmpty(labRptdetailObserList)) {
                        boolean b = labRptdetailObserService.saveBatch(labRptdetailObserList);
                    }
                }
            }
        }

        for (LabRptmain m : labRptmainYMs) {
            reportPreviewDto = new ReportPreviewDto();
            reportPreviewDto.setIsChecked(true);
            reportPreviewDto.setReportId(pubReportYM.getId());
            reportPreviewDto.setReportTemplateName(pubReportYM.getReportName());
            reportPreviewDtos.add(reportPreviewDto);
        }
        for (LabRptmain m : labRptmainYXs) {
            reportPreviewDto = new ReportPreviewDto();
            reportPreviewDto.setIsChecked(ToolsUtils.isNotEmpty(labRptmainYMs) && labRptmainYMs.size() > 0 ? false : true);
            reportPreviewDto.setReportId(pubReportYX.getId());
            reportPreviewDto.setReportTemplateName(pubReportYX.getReportName());
            reportPreviewDtos.add(reportPreviewDto);
        }

        return Result.succ(1, "成功", reportPreviewDtos);

    }

    @Autowired
    RedisSysParamHelper redisSysParamHelper;
    @Autowired
    LabReqMainMapper labReqMainMapper;
    @Autowired
    LabReqdetailDelMapper labReqdetailDelMapper;
    @Autowired
    LabReqStateMapper labReqStateMapper;
    @Autowired
    BacTestWorkFlowMapper bacTestWorkFlowMapper;
    @Autowired
    BacTestWorkFlowNodeMapper bacTestWorkFlowNodeMapper;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    LabMaininfoService labMaininfoService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    BacPublisFirstReportMapper bacPublisFirstReportMapper;
    @Autowired
    BacImageResultMapper bacImageResultMapper;
    @Autowired
    BacPublisSecReportMapper bacPublisSecReportMapper;
    @Autowired
    BacBloodCultrueMapper bacBloodCultrueMapper;
    @Autowired
    BacBloodCultrueService bacBloodCultrueService;
    @Autowired
    PubReportService pubReportService;

    @Override
    public Result findLabMaininfoPageList(LabMaininfoPageDto maininfoPageDto) {

        MPJLambdaWrapper<LabMaininfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.distinct();
        lambdaQueryWrapper.selectAll(LabMaininfo.class);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getBusinessType, LabMaininfo::getBusinessType);
        lambdaQueryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        lambdaQueryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        lambdaQueryWrapper.selectAs(LabReqMainQuery::getAddress, LabMaininfo::getAddress);
        lambdaQueryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        lambdaQueryWrapper.leftJoin(LabSampleType.class, on -> on.eq(LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType).eq(LabSampleType::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysOrgDepartment.class, on -> on.eq(SysOrgDepartment::getCode, LabMaininfo::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(PubEmployee.class, "req", on -> on.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        lambdaQueryWrapper.leftJoin(LabReqMainQuery.class, on -> on.eq(LabReqMainQuery::getReqNo, LabMaininfo::getReqNo).eq(LabReqMainQuery::getDelFlag, 0));
        if (CollectionUtil.isNotEmpty(maininfoPageDto.getFeeCodes())) {
            lambdaQueryWrapper.leftJoin(LabReqdetail.class, LabReqdetail::getReqNo, LabMaininfo::getReqNo);
            lambdaQueryWrapper.in(LabReqdetail::getFeeCode, maininfoPageDto.getFeeCodes());
        }
        //细菌添加耐药表型搜索条件
        if (CollectionUtil.isNotEmpty(maininfoPageDto.getResiPhenCodes())) {
            lambdaQueryWrapper.leftJoin(BacTestResult.class, on -> on.eq(LabMaininfo::getRptGroup, BacTestResult::getRptGroup).eq(LabMaininfo::getSampleNo, BacTestResult::getSampleNo).eq(LabMaininfo::getSampleda, BacTestResult::getSampleda).eq(BacTestResult::getDelFlag, 0));
            lambdaQueryWrapper.in(BacTestResult::getResiPhenNo, maininfoPageDto.getResiPhenCodes());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatId()), LabReqMainQuery::getPatId, maininfoPageDto.getPatId());

        //判断poct,报告单元添加poct过滤条件
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        if (StringUtils.isNotBlank(maininfoPageDto.getRptGroup())){
            lambdaQueryWrapper.eq( LabMaininfo::getRptGroup, maininfoPageDto.getRptGroup());
        }else {
          if(Objects.nonNull(maininfoPageDto.getPoct()) && maininfoPageDto.getPoct()==1){
              lambdaQueryWrapper.eq(LabRptGroup::getPoct, 1);
          }
        }

        if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
            Timestamp startTime = Timestamp.valueOf(maininfoPageDto.getSampledaBegin());
            Timestamp endTime = Timestamp.valueOf(maininfoPageDto.getSampledaEnd());
            lambdaQueryWrapper.ge(LabMaininfo::getSampleda, startTime);
            lambdaQueryWrapper.le(LabMaininfo::getSampleda, endTime);
        }
        if (StringUtils.isNotBlank(maininfoPageDto.getReqNoS()) && StringUtils.isNotBlank(maininfoPageDto.getReqNoE())) {
            lambdaQueryWrapper.ge(LabMaininfo::getReqNo, maininfoPageDto.getReqNoS());
            lambdaQueryWrapper.le(LabMaininfo::getReqNo, maininfoPageDto.getReqNoE());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqNo()), LabMaininfo::getReqNo, maininfoPageDto.getReqNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatNo()), LabMaininfo::getPatNo, maininfoPageDto.getPatNo());


//        lambdaQueryWrapper.like(StringUtils.isNotBlank(maininfoPageDto.getPatNa()), LabMaininfo::getPatNa, maininfoPageDto.getPatNa());

        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(maininfoPageDto.getPatNa())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabMaininfo::getPatNa, maininfoPageDto.getPatNa()).or().like(LabMaininfo::getPatPyName, maininfoPageDto.getPatNa().toLowerCase()));
        }

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getSex()), LabMaininfo::getSex, maininfoPageDto.getSex());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getBedNo()), LabMaininfo::getBedNo, maininfoPageDto.getBedNo());
        if (StringUtils.isNotBlank(maininfoPageDto.getSamplingTime())) {
            Timestamp samplingStart = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 00:00:00");
            Timestamp samplingEnd = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 23:59:59");
            lambdaQueryWrapper.ge(LabMaininfo::getSamplingTime, samplingStart);
            lambdaQueryWrapper.le(LabMaininfo::getSamplingTime, samplingEnd);
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getFeeType()), LabMaininfo::getFeeType, maininfoPageDto.getFeeType());
        lambdaQueryWrapper.eq(Objects.nonNull(maininfoPageDto.getIsChk()), LabMaininfo::getIsChk, maininfoPageDto.getIsChk());
        if (Objects.nonNull(maininfoPageDto.getIsPrint())) {
            if (maininfoPageDto.getIsPrint() == 1) {
                lambdaQueryWrapper.eq(LabMaininfo::getIsPrint, 1);
            } else {
                lambdaQueryWrapper.and(wrapper -> wrapper.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
            }
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDept()), LabMaininfo::getReqDept, maininfoPageDto.getReqDept());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDoctor()), LabMaininfo::getReqDoctor, maininfoPageDto.getReqDoctor());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getTestDoctor()), LabMaininfo::getTestDoctor, maininfoPageDto.getTestDoctor());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getChkDoctor()), LabMaininfo::getChkDoctor, maininfoPageDto.getChkDoctor());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatType()), LabMaininfo::getPatType, maininfoPageDto.getPatType());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getTraits()), LabMaininfo::getTraits, maininfoPageDto.getTraits());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getTestPurpose()), LabMaininfo::getTestPurpose, maininfoPageDto.getTestPurpose());

        //过滤无条码
        if (Objects.nonNull(maininfoPageDto.getIsFilterNoSpecCode()) && maininfoPageDto.getIsFilterNoSpecCode()) {
            lambdaQueryWrapper.isNotNull(LabMaininfo::getReqNo);
        }
        String orderBy = "";
        try {
            /*检验报告查询排列顺序*/
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("jybgcxplsx");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    orderBy = value;
                }
            }
        } catch (Exception ex) {
            orderBy = "";
        }
        if (ToolsUtils.isNotEmpty(orderBy)) {
            if ("asc".equals(orderBy)) {
                lambdaQueryWrapper.orderByAsc(LabMaininfo::getSampleda);
            } else if ("desc".equals(orderBy)) {
                lambdaQueryWrapper.orderByDesc(LabMaininfo::getSampleda);
            }
        } else {
            lambdaQueryWrapper.orderByAsc(LabMaininfo::getSampleda);
        }
        List<LabMaininfo> labMaininfoPage = labMaininfoService.list(lambdaQueryWrapper);
//        Page<LabMaininfo> page = new Page<>();
//        page.setCurrent(1);
//        page.setSize(100000);
//        Page<LabMaininfo> page1 = labMaininfoMapper.selectPage(page, lambdaQueryWrapper);
//        List<LabMaininfo> labMaininfoPage = page1.getRecords();
        //获取数据字典(病人类型、性别、证件类型)

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        List<SysUser> userList = sysUserService.list();

        for (LabMaininfo maininfo : labMaininfoPage) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
            if (StrUtil.isNotEmpty(maininfo.getChkDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getChkDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setChkDoctorNa(first.get().getRealname());
                }
            }
            if (StrUtil.isNotEmpty(maininfo.getTestDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getTestDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setTestDoctorNa(first.get().getRealname());
                }
            }
            if (StrUtil.isNotEmpty(maininfo.getPrintDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getPrintDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setPrintDoctorNa(first.get().getRealname());
                }
            }
        }

        return Result.succ(1, "查询成功", labMaininfoPage);
    }

    @Override
    public Result findLabMaininfoByHis(LabMaininfoPageDto maininfoPageDto) {
        MPJLambdaWrapper<LabMaininfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.distinct();
        lambdaQueryWrapper.selectAll(LabMaininfo.class);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getBusinessType, LabMaininfo::getBusinessType);
        lambdaQueryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        lambdaQueryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        lambdaQueryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        lambdaQueryWrapper.leftJoin(LabSampleType.class, on -> on.eq(LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType).eq(LabSampleType::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysOrgDepartment.class, on -> on.eq(SysOrgDepartment::getCode, LabMaininfo::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(PubEmployee.class, "req", on -> on.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        lambdaQueryWrapper.leftJoin(LabReqMainQuery.class, LabReqMainQuery::getReqNo, LabMaininfo::getReqNo);

        //查询不是细菌的检验结果
        lambdaQueryWrapper.ne(LabRptGroup::getBusinessType, "20");
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getRptGroup()), LabMaininfo::getRptGroup, maininfoPageDto.getRptGroup());
        if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
            Timestamp startTime = Timestamp.valueOf(maininfoPageDto.getSampledaBegin());
            Timestamp endTime = Timestamp.valueOf(maininfoPageDto.getSampledaEnd());
            lambdaQueryWrapper.ge(LabMaininfo::getSampleda, startTime);
            lambdaQueryWrapper.le(LabMaininfo::getSampleda, endTime);
        }

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqNo()), LabMaininfo::getReqNo, maininfoPageDto.getReqNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatId()), LabReqMainQuery::getPatId, maininfoPageDto.getPatId());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatNo()), LabMaininfo::getPatNo, maininfoPageDto.getPatNo());
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(maininfoPageDto.getPatNa())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabMaininfo::getPatNa, maininfoPageDto.getPatNa()).or().like(LabMaininfo::getPatPyName, maininfoPageDto.getPatNa().toLowerCase()));
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getBedNo()), LabMaininfo::getBedNo, maininfoPageDto.getBedNo());
        lambdaQueryWrapper.eq(Objects.nonNull(maininfoPageDto.getIsChk()), LabMaininfo::getIsChk, maininfoPageDto.getIsChk());
        if (Objects.nonNull(maininfoPageDto.getIsPrint())) {
            if (maininfoPageDto.getIsPrint() == 1) {
                lambdaQueryWrapper.eq(LabMaininfo::getIsPrint, 1);
            } else {
                lambdaQueryWrapper.and(wrapper -> wrapper.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
            }
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDept()), LabMaininfo::getReqDept, maininfoPageDto.getReqDept());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDoctor()), LabMaininfo::getReqDoctor, maininfoPageDto.getReqDoctor());
        List<LabMaininfo> labMaininfoPage = labMaininfoService.list(lambdaQueryWrapper);

        List<LabMaininfo> bacMainInfo = getBacMainInfo(maininfoPageDto);
        labMaininfoPage.addAll(bacMainInfo);

        String orderBy = "";
        try {
            //*检验报告查询排列顺序*//*
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("jybgcxplsx");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                String value = r1.get(0).getValue();
                if (ToolsUtils.isNotEmpty(value)) {
                    orderBy = value;
                }
            }
        } catch (Exception ex) {
            orderBy = "";
        }
        if (ToolsUtils.isNotEmpty(orderBy)) {
            if ("asc".equals(orderBy)) {
                // labMaininfoPage 集合根据时间进行升序排列
                labMaininfoPage.stream().sorted(Comparator.comparing(LabMaininfo::getSampleda)).collect(Collectors.toList());
            } else if ("desc".equals(orderBy)) {
                labMaininfoPage.stream().sorted(Comparator.comparing(LabMaininfo::getSampleda, Comparator.reverseOrder())).collect(Collectors.toList());
            }
        } else {
            labMaininfoPage.stream().sorted(Comparator.comparing(LabMaininfo::getSampleda)).collect(Collectors.toList());
        }



        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        List<SysUser> userList = sysUserService.list();

        for (LabMaininfo maininfo : labMaininfoPage) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
            if (StrUtil.isNotEmpty(maininfo.getChkDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getChkDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setChkDoctorNa(first.get().getRealname());
                }
            }
            if (StrUtil.isNotEmpty(maininfo.getTestDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getTestDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setTestDoctorNa(first.get().getRealname());
                }
            }
            if (StrUtil.isNotEmpty(maininfo.getPrintDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getPrintDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setPrintDoctorNa(first.get().getRealname());
                }
            }
        }
        return Result.succ(1, "查询成功", labMaininfoPage);
    }


    public List<LabMaininfo> getBacMainInfo(LabMaininfoPageDto maininfoPageDto) {
        MPJLambdaWrapper<LabMaininfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.distinct();
        lambdaQueryWrapper.selectAll(LabMaininfo.class);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getBusinessType, LabMaininfo::getBusinessType);
        lambdaQueryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        lambdaQueryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        lambdaQueryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        lambdaQueryWrapper.leftJoin(LabSampleType.class, on -> on.eq(LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType).eq(LabSampleType::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysOrgDepartment.class, on -> on.eq(SysOrgDepartment::getCode, LabMaininfo::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(PubEmployee.class, "req", on -> on.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfo::getRptGroup);
        lambdaQueryWrapper.leftJoin(LabReqMainQuery.class, LabReqMainQuery::getReqNo, LabMaininfo::getReqNo);

        //查询不是细菌的检验结果
        lambdaQueryWrapper.eq(LabRptGroup::getBusinessType, "20");
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getRptGroup()), LabMaininfo::getRptGroup, maininfoPageDto.getRptGroup());
        if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
            Timestamp startTime = Timestamp.valueOf(maininfoPageDto.getSampledaBegin());
            Timestamp endTime = Timestamp.valueOf(maininfoPageDto.getSampledaEnd());
            lambdaQueryWrapper.ge(LabMaininfo::getSampleda, startTime);
            lambdaQueryWrapper.le(LabMaininfo::getSampleda, endTime);
        }

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqNo()), LabMaininfo::getReqNo, maininfoPageDto.getReqNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatNo()), LabMaininfo::getPatNo, maininfoPageDto.getPatNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatId()), LabReqMainQuery::getPatId, maininfoPageDto.getPatId());
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(maininfoPageDto.getPatNa())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabMaininfo::getPatNa, maininfoPageDto.getPatNa()).or().like(LabMaininfo::getPatPyName, maininfoPageDto.getPatNa().toLowerCase()));
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getBedNo()), LabMaininfo::getBedNo, maininfoPageDto.getBedNo());
        /**
         * 查询出所有的微生物,过滤没有发布过得数据
         */
        lambdaQueryWrapper.isNotNull(LabMaininfo::getBacFlowNode);
        if (Objects.nonNull(maininfoPageDto.getIsPrint())) {
            if (maininfoPageDto.getIsPrint() == 1) {
                lambdaQueryWrapper.eq(LabMaininfo::getIsPrint, 1);
            } else {
                lambdaQueryWrapper.and(wrapper -> wrapper.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
            }
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDept()), LabMaininfo::getReqDept, maininfoPageDto.getReqDept());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDoctor()), LabMaininfo::getReqDoctor, maininfoPageDto.getReqDoctor());
        List<LabMaininfo> labMaininfoPage = labMaininfoService.list(lambdaQueryWrapper);
        return labMaininfoPage;
    }

    /*报告查询*/
    @Override
    public Result findBacReportList(BacRptOverviewParam input) {
        BacRptOverviewDto res = new BacRptOverviewDto();
        List<BacRptOverviewItemDto> r1 = findFirstReportList(input.getSampleNo(), input.getRptGroup(), input.getSampleda());
        if (CollectionUtils.isNotEmpty(r1)) {
            res.setFirstRptList(r1);
        }
        List<BacRptOverviewItemDto> r2 = findSecReportList(input.getSampleNo(), input.getRptGroup(), input.getSampleda());
        if (CollectionUtils.isNotEmpty(r2)) {
            res.setSecRptList(r2);
        }
        List<BacRptOverviewItemDto> r3 = findFinalReportList(input.getSampleNo(), input.getRptGroup(), input.getSampleda());
        if (CollectionUtils.isNotEmpty(r3)) {
            res.setFinalRptList(r3);
        }
        return Result.succ(1, "查询成功", res);
    }

    public List<BacRptOverviewItemDto> findFirstReportList(String sampleNo, String rptGroup, Timestamp sampleda) {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return null;
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();

        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && "001".equals(map.get("pointsCode"))).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(filteredList)) {
            return null;
        }

        String pointId = filteredList.get(0).get("commonId").toString();

        /*计算使用的模板Id,模板名称*/
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        pubRptQuery.eq(PubReport::getIsUse, 1);
        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return null;
        }
        PubReport pubReport = pubReportList.get(0);

        /*查询初级报告发布*/
        LambdaQueryWrapper<BacPublisFirstReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Timestamp timestamp = new Timestamp(sampleda.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        lambdaQueryWrapper.ge(BacPublisFirstReport::getSampleda, startTime);
        lambdaQueryWrapper.le(BacPublisFirstReport::getSampleda, endTime);
        lambdaQueryWrapper.eq(BacPublisFirstReport::getRptGroup, rptGroup);
        lambdaQueryWrapper.eq(BacPublisFirstReport::getSampleNo, sampleNo);
        lambdaQueryWrapper.and(p -> p.ne(BacPublisFirstReport::getIsCancel, 1).or().isNull(BacPublisFirstReport::getIsCancel));
        List<BacPublisFirstReport> bacPublisSecReports = bacPublisFirstReportMapper.selectList(lambdaQueryWrapper);

        List<ReportPreviewDto> resList = new ArrayList<>();
        List<BacRptOverviewItemDto> rptOverviewItemDtoList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(bacPublisSecReports)) {
            String idsStr = bacPublisSecReports.stream().map(BacPublisFirstReport::getId).collect(Collectors.joining(","));
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(idsStr);
            _m.setReportId(pubReport.getId());
            _m.setIsChecked(false);
            _m.setReportTemplateName(pubReport.getName());
            resList.add(_m);
            /*查询血培养集合*/
            List<String> bloodCulResultIds = bacPublisSecReports.stream().map(BacPublisFirstReport::getBloodcultureId).collect(Collectors.toList());
            LambdaQueryWrapper<BacBloodCultrue> bacBloodCultrueQuery = new LambdaQueryWrapper<>();
            bacBloodCultrueQuery.eq(BacBloodCultrue::getDelFlag, 0);
            bacBloodCultrueQuery.in(BacBloodCultrue::getId, bloodCulResultIds);
            List<BacBloodCultrue> bacBloodCultrueList = bacBloodCultrueMapper.selectList(bacBloodCultrueQuery);

            for (BacPublisFirstReport bacPublisFirstReport : bacPublisSecReports) {
                BacRptOverviewItemDto itemDto = new BacRptOverviewItemDto();
                itemDto.setId(idsStr);
                itemDto.setReportId(pubReport.getId());
                itemDto.setIsChecked(false);
                itemDto.setIsActived(false);
                itemDto.setRptGroup(bacPublisFirstReport.getRptGroup());
                itemDto.setSampleNo(bacPublisFirstReport.getSampleNo());
                itemDto.setSampldeda(bacPublisFirstReport.getSampleda());
                itemDto.setPageUnit(pubReport.getPaperSize());
                itemDto.setReportTemplateName(pubReport.getName());

                if (ToolsUtils.isNotEmpty(bacBloodCultrueList)) {
                    BacBloodCultrue bacBloodCultrue = bacBloodCultrueList.stream().filter(a -> bacPublisFirstReport.getBloodcultureId().equals(a.getId())).findFirst().orElse(null);
                    if (bacBloodCultrue != null) {
                        itemDto.setTitle(bacBloodCultrue.getCulMediumNa());
                        if (ToolsUtils.isNotEmpty(bacBloodCultrue.getIsPositive()) && bacBloodCultrue.getIsPositive() == 1) {
                            itemDto.setContent1("阳性");
                        } else {
                            itemDto.setContent1("阴性");
                        }
                        itemDto.setContent2(bacBloodCultrue.getExpoTime());
                        if (ToolsUtils.isNotEmpty(bacBloodCultrue.getResultTime())) {
                            Timestamp timestamp1 = new Timestamp(bacBloodCultrue.getResultTime().getTime());
                            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                            String formattedDate1 = sdf.format(timestamp1);
                            itemDto.setContent3(formattedDate1);

                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String formattedDate2 = sdf.format(timestamp1);
                            itemDto.setContent5(formattedDate2);
                        }
                        if (ToolsUtils.isNotEmpty(bacBloodCultrue.getIsAlarm()) && bacBloodCultrue.getIsAlarm() == 1) {
                            itemDto.setContent4("是");
                        } else {
                            itemDto.setContent4("");
                        }
                    }
                }
                rptOverviewItemDtoList.add(itemDto);
            }
        }
        return rptOverviewItemDtoList;
    }

    public List<BacRptOverviewItemDto> findSecReportList(String sampleNo, String rptGroup, Timestamp sampleda) {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = sysBasDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return null;
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();

        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && "002".equals(map.get("pointsCode"))).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(filteredList)) {
            return null;
        }

        String pointId = filteredList.get(0).get("commonId").toString();
        Timestamp timestamp = new Timestamp(sampleda.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");

        /*查询是否有图片*/
        LambdaQueryWrapper<BacImageResult> bacImageResultQuery = new LambdaQueryWrapper<>();
        bacImageResultQuery.eq(BacImageResult::getDelFlag, 0);
        bacImageResultQuery.eq(BacImageResult::getSampleNo, sampleNo);
        bacImageResultQuery.eq(BacImageResult::getIsSelected, 1);
        bacImageResultQuery.in(BacImageResult::getRptGroup, rptGroup);
        bacImageResultQuery.ge(BacImageResult::getSampleda, startTime);
        bacImageResultQuery.le(BacImageResult::getSampleda, endTime);
        //bacImageResultQuery.in(BacImageResult::getSampleda, input.getSampleda());

        //增加菌株匹配选择，若菌株号存在，则匹配
        int imgCount = bacImageResultMapper.selectCount(bacImageResultQuery);
        /*计算使用的模板Id,模板名称*/
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        if (imgCount > 0) {
            pubRptQuery.eq(PubReport::getIncludeImages, 1);
        }
        pubRptQuery.eq(PubReport::getIsUse, 1);

        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return null;
        }
        PubReport pubReport = pubReportList.get(0);

        /*查询二级报告发布*/
        LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
        lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
        lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, rptGroup);
        lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, sampleNo);
        lambdaQueryWrapper.eq(BacPublisSecReport::getDelFlag, 0);
        lambdaQueryWrapper.and(p -> p.ne(BacPublisSecReport::getIsCancel, 1).or().isNull(BacPublisSecReport::getIsCancel));
        List<BacPublisSecReport> bacPublisSecReports = bacPublisSecReportMapper.selectList(lambdaQueryWrapper);

        List<ReportPreviewDto> resList = new ArrayList<>();
        List<BacRptOverviewItemDto> rptOverviewItemDtoList = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(bacPublisSecReports)) {
            String idsStr = bacPublisSecReports.stream().map(BacPublisSecReport::getId).collect(Collectors.joining(","));
            ReportPreviewDto _m = new ReportPreviewDto();
            _m.setId(idsStr);
            _m.setReportId(pubReport.getId());
            _m.setIsChecked(true);
            _m.setReportTemplateName(pubReport.getName());
            resList.add(_m);

            for (BacPublisSecReport bacPublisFirstReport : bacPublisSecReports) {
                BacRptOverviewItemDto itemDto = new BacRptOverviewItemDto();
                itemDto.setId(idsStr);
                itemDto.setReportId(pubReport.getId());
                itemDto.setIsChecked(false);
                itemDto.setIsActived(false);
                itemDto.setRptGroup(bacPublisFirstReport.getRptGroup());
                itemDto.setSampleNo(bacPublisFirstReport.getSampleNo());
                itemDto.setSampldeda(bacPublisFirstReport.getSampleda());
                itemDto.setPageUnit(pubReport.getPaperSize());
                itemDto.setReportTemplateName(pubReport.getName());

                /*查询血培养集合*/
                LambdaQueryWrapper<BacObserResult> bacObserResultQuery = new LambdaQueryWrapper<>();
                bacObserResultQuery.eq(BacObserResult::getDelFlag, 0);
                bacObserResultQuery.eq(BacObserResult::getRptGroup, rptGroup);
                bacObserResultQuery.eq(BacObserResult::getSampleNo, sampleNo);
                bacObserResultQuery.ge(BacObserResult::getSampleda, startTime);
                bacObserResultQuery.le(BacObserResult::getSampleda, endTime);
                bacObserResultQuery.eq(BacObserResult::getTestFlowNo, bacPublisFirstReport.getTestFlowNo());
                bacObserResultQuery.eq(BacObserResult::getTestNodeNo, bacPublisFirstReport.getTestNodeNo());
                bacObserResultQuery.eq(BacObserResult::getIsolateNum, bacPublisFirstReport.getStrainNo());
                List<BacObserResult> bacObserResultList = bacObserResultMapper.selectList(bacObserResultQuery);

                if (ToolsUtils.isNotEmpty(bacObserResultList)) {
                    BacObserResult bacObserResult = bacObserResultList.get(0);
                    if (bacObserResult != null) {
                        itemDto.setTitle("培养观察报告");
                        if (ToolsUtils.isNotEmpty(bacObserResult.getMorphologyName())) {
                            itemDto.setContent1(bacObserResult.getMorphologyName());
                        } else {
                            itemDto.setContent1("");
                        }
                        if (ToolsUtils.isNotEmpty(bacObserResult.getCreateTime())) {
                            Timestamp timestamp1 = new Timestamp(bacObserResult.getCreateTime().getTime());
                            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                            String formattedDate1 = sdf.format(timestamp1);

                            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String formattedDate2 = sdf.format(timestamp1);
                            itemDto.setContent5(formattedDate2);
                        }
                        if (ToolsUtils.isNotEmpty(bacObserResult.getIsAlarm()) && bacObserResult.getIsAlarm()) {
                            itemDto.setContent4("是");
                        } else {
                            itemDto.setContent4("");
                        }
                    }
                }
                rptOverviewItemDtoList.add(itemDto);
            }

        }
        return rptOverviewItemDtoList;
    }

    public List<BacRptOverviewItemDto> findFinalReportList(String sampleNo, String rptGroup, Timestamp sampleda) {
        MPJLambdaWrapper<LabRptmain> queryWrapperSerach = new MPJLambdaWrapper<>();
        queryWrapperSerach.selectAll(LabRptmain.class);
        queryWrapperSerach.selectAs("pubrpt", PubReport::getName, LabRptmain::getTemplateName);
        queryWrapperSerach.eq(LabRptmain::getDelFlag, 0);
        queryWrapperSerach.eq(LabRptmain::getIsFinalReport, 1);
        queryWrapperSerach.eq(LabRptmain::getRptGroup, rptGroup);
        queryWrapperSerach.eq(LabRptmain::getSampleNo, sampleNo);
        Timestamp timestamp = new Timestamp(sampleda.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
        queryWrapperSerach.ge(LabRptmain::getSampleda, startTime);
        queryWrapperSerach.le(LabRptmain::getSampleda, endTime);
        queryWrapperSerach.eq(LabRptmain::getIsFinalReport, 1);
        queryWrapperSerach.leftJoin(PubReport.class, "pubrpt", p -> p.eq(PubReport::getId, LabRptmain::getRptTemplateCode).isNotNull(PubReport::getCode));

        List<LabRptmain> labRptmainList = labRptmainMapper.selectList(queryWrapperSerach);
        List<ReportPreviewDto> resList = new ArrayList<>();
        List<BacRptOverviewItemDto> rptOverviewItemDtoList = new ArrayList<>();

        /*查询血培养集合*/
        LambdaQueryWrapper<BacTestResult> bacTestResultQuery = new LambdaQueryWrapper<>();
        bacTestResultQuery.eq(BacTestResult::getDelFlag, 0);
        bacTestResultQuery.eq(BacTestResult::getRptGroup, rptGroup);
        bacTestResultQuery.eq(BacTestResult::getSampleNo, sampleNo);
        bacTestResultQuery.ge(BacTestResult::getSampleda, startTime);
        bacTestResultQuery.le(BacTestResult::getSampleda, endTime);
        List<BacTestResult> bacTestResultList = bacTestResultMapper.selectList(bacTestResultQuery);

        /*获取采用哪个阳性报告*/
        PubReport ympReport = pubReportService.getPubReportByDictDetailVaule("004");
        /*获取采用哪个阴性报告*/
        PubReport yxpReport = pubReportService.getPubReportByDictDetailVaule("003");
        Integer ymCount = 0;
        Integer yxCount = 0;
        for (BacTestResult tr : bacTestResultList) {
            BacRptOverviewItemDto itemDto = new BacRptOverviewItemDto();
            if (ToolsUtils.isNotEmpty(tr.getGermNo())) {
                List<LabRptmain> aimList = labRptmainList.stream().filter(p -> p.getRptTemplateCode().equals(ympReport.getId())).collect(Collectors.toList());
                LabRptmain aimEntry = ToolsUtils.isNotEmpty(aimList) ? aimList.get(ymCount) : null;
                if (ToolsUtils.isNotEmpty(aimEntry)) {
                    /*阳性*/
                    itemDto.setId(aimEntry.getId());
                    itemDto.setReportId(aimEntry.getRptTemplateCode());
                    itemDto.setIsChecked(false);
                    itemDto.setIsActived(false);
                    itemDto.setRptGroup(tr.getRptGroup());
                    itemDto.setSampleNo(tr.getSampleNo());
                    itemDto.setSampldeda(tr.getSampleda());
                    itemDto.setPageUnit(aimEntry.getPageUnit());
                    itemDto.setReportTemplateName(aimEntry.getTemplateName());
                    itemDto.setTitle(tr.getGermNa());
                    itemDto.setContent1("阳性");
                    itemDto.setContent2(tr.getResiPhenNa());
                    if (ToolsUtils.isNotEmpty(tr.getOperateDate())) {
                        Timestamp timestamp1 = new Timestamp(tr.getOperateDate().getTime());
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate1 = sdf.format(timestamp1);

                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String formattedDate2 = sdf.format(timestamp1);
                        itemDto.setContent5(formattedDate2);
                    }
                    ymCount++;
                    rptOverviewItemDtoList.add(itemDto);
                }
            } else {
                /*阴性*/
                List<LabRptmain> aimList = labRptmainList.stream().filter(p -> p.getRptTemplateCode().equals(yxpReport.getId())).collect(Collectors.toList());
                LabRptmain aimEntry = ToolsUtils.isNotEmpty(aimList) ? aimList.get(yxCount) : null;
                if (ToolsUtils.isNotEmpty(aimEntry)) {
                    /*阳性*/
                    itemDto.setId(aimEntry.getId());
                    itemDto.setReportId(aimEntry.getRptTemplateCode());
                    itemDto.setIsChecked(false);
                    itemDto.setIsActived(false);
                    itemDto.setRptGroup(tr.getRptGroup());
                    itemDto.setSampleNo(tr.getSampleNo());
                    itemDto.setSampldeda(tr.getSampleda());
                    itemDto.setPageUnit(aimEntry.getPageUnit());
                    itemDto.setReportTemplateName(aimEntry.getTemplateName());
                    itemDto.setTitle(tr.getGermNa());
                    itemDto.setContent1("阴性");
                    if (ToolsUtils.isNotEmpty(tr.getOperateDate())) {
                        Timestamp timestamp1 = new Timestamp(tr.getOperateDate().getTime());
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
                        String formattedDate1 = sdf.format(timestamp1);

                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String formattedDate2 = sdf.format(timestamp1);
                        itemDto.setContent5(formattedDate2);
                    }
                    yxCount++;
                    rptOverviewItemDtoList.add(itemDto);
                }
            }

        }

        return rptOverviewItemDtoList;
    }

    public Result findLabMaininfoBac(LabMaininfo labMaininfo) {

        MPJLambdaWrapper<LabMaininfo> queryWrapper = new MPJLambdaWrapper<>();
        SysUser sysUser = RedisUserManager.getUser();
        queryWrapper.distinct();
        queryWrapper.selectAll(LabMaininfo.class);
        queryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfo::getSampleTypeNa);
        queryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfo::getReqDeptNa);
        queryWrapper.selectAs("req", PubEmployee::getName, LabMaininfo::getReqDoctorNa);
        queryWrapper.selectAs("test", SysUser::getRealname, LabMaininfo::getTestDoctorNa);
        queryWrapper.selectAs("chk", SysUser::getRealname, LabMaininfo::getChkDoctorNa);
        queryWrapper.selectAs("rechk", SysUser::getRealname, LabMaininfo::getReChkDoctorNa);
        queryWrapper.selectAs("prt", SysUser::getRealname, LabMaininfo::getPrintDoctorNa);
        queryWrapper.selectAs("sampl", SysUser::getRealname, LabMaininfo::getSamplingDoctorNa);
        queryWrapper.selectAs("signer", SysUser::getRealname, LabMaininfo::getSignerDoctorNa);
        queryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfo::getRptGroupNa);
        queryWrapper.selectAs("reqm", LabReqMainQuery::getId, LabMaininfo::getReqMainId);
        queryWrapper.leftJoin(LabSampleType.class, p -> p.eq(LabSampleType::getSampleTypeCode, LabMaininfo::getSampleType).eq(LabSampleType::getDelFlag, 0));
        queryWrapper.leftJoin(SysOrgDepartment.class, p -> p.eq(SysOrgDepartment::getCode, LabMaininfo::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        queryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabMaininfo::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        queryWrapper.leftJoin(SysUser.class, "test", p -> p.eq(SysUser::getUsername, LabMaininfo::getTestDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "chk", p -> p.eq(SysUser::getUsername, LabMaininfo::getChkDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "rechk", p -> p.eq(SysUser::getUsername, LabMaininfo::getReChkDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "prt", p -> p.eq(SysUser::getUsername, LabMaininfo::getPrintDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "sampl", p -> p.eq(SysUser::getUsername, LabMaininfo::getSamplingDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(SysUser.class, "signer", p -> p.eq(SysUser::getUsername, LabMaininfo::getSignerDoctor).eq(SysUser::getDelFlag, 0).isNotNull(SysUser::getUsername).ne(SysUser::getUsername, ""));
        queryWrapper.leftJoin(LabRptGroup.class, "rptgrp", p -> p.eq(LabRptGroup::getRptGroup, LabMaininfo::getRptGroup).eq(LabRptGroup::getDelFlag, 0));
        queryWrapper.leftJoin(LabReqMainQuery.class, "reqm", p -> p.eq(LabReqMainQuery::getReqNo, LabMaininfo::getReqNo).eq(LabReqMainQuery::getDelFlag, 0));
        queryWrapper.leftJoin(LabReqdetailDel.class, p -> p.eq(LabReqdetailDel::getReqNo, LabMaininfo::getReqNo).eq(LabReqdetailDel::getDelFlag, 0));
        queryWrapper.leftJoin(LabFeeItem.class, p -> p.eq(LabFeeItem::getFeeCode, LabReqdetailDel::getFeeCode).eq(LabFeeItem::getDelFlag, 0));
        StringBuffer existsSql = new StringBuffer("SELECT 1 FROM BAC_RPTRESULT t2 WHERE t.SAMPLEDA = t2.SAMPLEDA AND t.RPT_GROUP = t2.RPT_GROUP AND t.SAMPLE_NO = t2.SAMPLE_NO AND t2.DEL_FLAG = 0 AND t2.GERM_NO IS NOT NULL AND  t2.GERM_NO != '' ");
        if (ToolsUtils.isNotEmpty(labMaininfo.getIsPositive()) && labMaininfo.getIsPositive().equals("2")) {
            queryWrapper.exists(existsSql.toString());
        } else if (ToolsUtils.isNotEmpty(labMaininfo.getIsPositive()) && labMaininfo.getIsPositive().equals("3")) {
            queryWrapper.notExists(existsSql.toString());
        }
        if (ToolsUtils.isNotEmpty(labMaininfo.getIsExperiment()) && labMaininfo.getIsExperiment()==1){
            queryWrapper.leftJoin(BacObserResult.class, p -> p
                    .eq(BacObserResult::getSampleda, LabMaininfo::getSampleda)
                    .eq(BacObserResult::getSampleNo, LabMaininfo::getSampleNo)
                    .eq(BacObserResult::getRptGroup, LabMaininfo::getRptGroup)
                    .eq(BacObserResult::getDelFlag, 0));
            queryWrapper.and(item->item.isNotNull(BacObserResult::getExperiment).or().eq(BacObserResult::getExperiment, ""));

        }
        //只查询染色项目的
        if (ToolsUtils.isNotEmpty(labMaininfo.getIsStaining()) && !labMaininfo.getIsStaining().equals("2")) {
            if (labMaininfo.getIsStaining().equals("1")){
                queryWrapper.eq(LabFeeItem::getIsStaining, labMaininfo.getIsStaining());
            }else {
                queryWrapper.and(item->item.isNull(LabFeeItem::getIsStaining).or().eq(LabFeeItem::getIsStaining, labMaininfo.getIsStaining()));
            }
        }


        queryWrapper.eq(Objects.nonNull(sysUser), LabMaininfo::getOrgId, sysUser.getOrgId());
        queryWrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getRptGroup, labMaininfo.getRptGroup());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getId()), LabMaininfo::getId, labMaininfo.getId());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getPatType()), LabMaininfo::getPatType, labMaininfo.getPatType());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getSampleNo()), LabMaininfo::getSampleNo, labMaininfo.getSampleNo());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getSampleType()), LabMaininfo::getSampleType, labMaininfo.getSampleType());
        queryWrapper.eq(StringUtils.isNotBlank(labMaininfo.getReqPurposeId()), LabReqMainQuery::getPurposeNo, labMaininfo.getReqPurposeId());
        queryWrapper.like(StringUtils.isNotBlank(labMaininfo.getPatNa()), LabMaininfo::getPatNa, labMaininfo.getPatNa());
        queryWrapper.like(StringUtils.isNotBlank(labMaininfo.getPatNo()), LabMaininfo::getPatNo, labMaininfo.getPatNo());
        //是否是从筛选中查询
        if (Objects.nonNull(labMaininfo.getQueryDay())) {
            Timestamp startOfDay =null;
            Timestamp endOfDay =null;
            Integer queryDay = labMaininfo.getQueryDay();
            if (queryDay == 58){
                // 获取当前时间
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, - 8); // 减去对应天数
                // 设置到当天的开始时间
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                 startOfDay = new Timestamp(calendar.getTimeInMillis());

                // 设置到当天的结束时间
                Calendar calendar1 = Calendar.getInstance();
                calendar1.add(Calendar.DAY_OF_MONTH, - 5); // 减去对应天数
                calendar1.set(Calendar.HOUR_OF_DAY, 23);
                calendar1.set(Calendar.MINUTE, 59);
                calendar1.set(Calendar.SECOND, 59);
                calendar1.set(Calendar.MILLISECOND, 999);
                 endOfDay = new Timestamp(calendar1.getTimeInMillis());
            }else {
                // 获取当前时间
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, - labMaininfo.getQueryDay()); // 减去对应天数
                // 设置到当天的开始时间
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);
                 startOfDay = new Timestamp(calendar.getTimeInMillis());

                // 设置到当天的结束时间
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);
                calendar.set(Calendar.MILLISECOND, 999);
                 endOfDay = new Timestamp(calendar.getTimeInMillis());
            }

            queryWrapper.ge(LabMaininfo::getSampleda, startOfDay);
            queryWrapper.le(LabMaininfo::getSampleda, endOfDay);
        } else {
            if (StringUtils.isNotBlank(labMaininfo.getTestTimeS())) {
                Timestamp testTimeS = Timestamp.valueOf(labMaininfo.getTestTimeS() + " 00:00:00");
                queryWrapper.ge(LabMaininfo::getSampleda, testTimeS);
            }
            if (StringUtils.isNotBlank(labMaininfo.getTestTimeE())) {
                Timestamp testTimeE = Timestamp.valueOf(labMaininfo.getTestTimeE() + " 23:59:59");
                queryWrapper.le(LabMaininfo::getSampleda, testTimeE);
            }
            if (StringUtils.isNotBlank(labMaininfo.getChkTimeS())) {
                Timestamp chkTimeS = Timestamp.valueOf(labMaininfo.getChkTimeS() + " 00:00:00");
                queryWrapper.ge(LabMaininfo::getChkTime, chkTimeS);
            }
            if (StringUtils.isNotBlank(labMaininfo.getChkTimeE())) {
                Timestamp chkTimeE = Timestamp.valueOf(labMaininfo.getChkTimeE() + " 23:59:59");
                queryWrapper.le(LabMaininfo::getChkTime, chkTimeE);
            }
        }


        /*快速查询条件*/
        if (!BeanUtil.isEmpty(labMaininfo.getStateCode())) {
            switch (labMaininfo.getStateCode()) {
                case 1://已审核
                    queryWrapper.eq(LabMaininfo::getIsChk, 2);
                    break;
                case 2://未审核
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));
                    break;
                case 3://已初审
                    queryWrapper.eq(LabMaininfo::getIsChk, 1);
                    break;
                case 4: //已打印
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 5://未打印
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
                case 6://已审核已打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 2);
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 7://已审核未打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 2);
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
                case 8://未审核已打印
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 9://未审核未打印
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
                case 10://初审已打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 1);
                    queryWrapper.eq(LabMaininfo::getIsPrint, 1);
                    break;
                case 11://初审未打印
                    queryWrapper.eq(LabMaininfo::getIsChk, 1);
                    queryWrapper.and(p -> p.eq(LabMaininfo::getIsPrint, 0).or().isNull(LabMaininfo::getIsPrint));
                    break;
            }
        }

        if (!BeanUtil.isEmpty(labMaininfo.getIsSelf())) {
            queryWrapper.and(p -> p.eq(LabMaininfo::getTestDoctor, sysUser.getUsername()).or().eq(LabMaininfo::getChkDoctor, sysUser.getUsername()));
        }

        queryWrapper.orderByAsc(LabMaininfo::getSampleNo);
        queryWrapper.orderByAsc(LabMaininfo::getSampleda);

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabMaininfo maininfo : labMaininfos) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }


        MPJLambdaWrapper<BacTestResult> mpjResLambdaWrapper = new MPJLambdaWrapper<>();

        mpjResLambdaWrapper.selectAll(BacTestResult.class)
                .innerJoin(BacResistantPhenotypeDict.class,p->p.eq(BacResistantPhenotypeDict::getCode,BacTestResult::getResiPhenNo).eq(BacResistantPhenotypeDict::getResistantTypeNo,"MDR").eq(BacResistantPhenotypeDict::getDelFlag,0));

        if (StringUtils.isNotBlank(labMaininfo.getTestTimeS())) {
            Timestamp testTimeS = Timestamp.valueOf(labMaininfo.getTestTimeS() + " 00:00:00");
            mpjResLambdaWrapper.ge(BacTestResult::getSampleda, testTimeS);
        }
        if (StringUtils.isNotBlank(labMaininfo.getTestTimeE())) {
            Timestamp testTimeE = Timestamp.valueOf(labMaininfo.getTestTimeE() + " 23:59:59");
            mpjResLambdaWrapper.le(BacTestResult::getSampleda, testTimeE);
        }

        mpjResLambdaWrapper.isNotNull(BacTestResult::getResiPhenNo)
                .eq(BacTestResult::getRptGroup,labMaininfo.getRptGroup())
                .eq(BacTestResult::getDelFlag, 0);

        List<BacTestResult> bacTestResultList = bacTestResultMapper.selectList(mpjResLambdaWrapper);
        //bacTestResultList没有数据
        if (CollectionUtils.isNotEmpty(bacTestResultList)) {
            labMaininfos.forEach(maininfo -> {
                bacTestResultList.forEach(bacTestResult -> {
                    if (maininfo.getSampleNo().equals(bacTestResult.getSampleNo()) && maininfo.getSampleda().equals(bacTestResult.getSampleda()) && maininfo.getRptGroup().equals(bacTestResult.getRptGroup())) {
                        maininfo.setIsMdr(1);
                    }
                });
            });
        }
        //增加补费记录标识
        LambdaQueryWrapper<BacDrugTestResult> lambdaQueryWrapper111 = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(labMaininfo.getTestTimeS())) {
            Timestamp testTimeS = Timestamp.valueOf(labMaininfo.getTestTimeS() + " 00:00:00");
            lambdaQueryWrapper111.ge(BacDrugTestResult::getSampleda, testTimeS);
        }
        if (StringUtils.isNotBlank(labMaininfo.getTestTimeE())) {
            Timestamp testTimeE = Timestamp.valueOf(labMaininfo.getTestTimeE() + " 23:59:59");
            lambdaQueryWrapper111.le(BacDrugTestResult::getSampleda, testTimeE);
        }
        lambdaQueryWrapper111.eq(BacDrugTestResult::getRptGroup, labMaininfo.getRptGroup());
        lambdaQueryWrapper111.eq(BacDrugTestResult::getDelFlag, 0);
        //查询药敏结果的所有信息 需要补费
        List<BacDrugTestResult> drugList = bacDrugTestResultService.list(lambdaQueryWrapper111);
        if (CollectionUtils.isNotEmpty(drugList)) {
            labMaininfos.forEach(maininfo -> {
                drugList.forEach(drug -> {
                    if (maininfo.getSampleNo().equals(drug.getSampleNo()) && maininfo.getSampleda().equals(drug.getSampleda()) && maininfo.getRptGroup().equals(drug.getRptGroup())) {
                        maininfo.setAddFee(1);
                    }
                });
            });
        }

        LambdaQueryWrapper<BacAddFee> lambdaQueryWrapper222 = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(labMaininfo.getTestTimeS())) {
            Timestamp testTimeS = Timestamp.valueOf(labMaininfo.getTestTimeS() + " 00:00:00");
            lambdaQueryWrapper222.ge(BacAddFee::getSampleda, testTimeS);
        }
        if (StringUtils.isNotBlank(labMaininfo.getTestTimeE())) {
            Timestamp testTimeE = Timestamp.valueOf(labMaininfo.getTestTimeE() + " 23:59:59");
            lambdaQueryWrapper222.le(BacAddFee::getSampleda, testTimeE);
        }
        lambdaQueryWrapper222.eq(BacAddFee::getRptGroup, labMaininfo.getRptGroup()).eq(BacAddFee::getDelFlag, 0);
        //查询补费记录信息
        List<BacAddFee> addFeeList = bacAddFeeService.list(lambdaQueryWrapper222);
        //过滤出补费失败的记录
        List<BacAddFee> errorList = addFeeList.stream().filter(fee -> fee.getIsCharge() != null && fee.getIsCharge() == 0 && StrUtil.isNotEmpty(fee.getMessage())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(addFeeList)) {
            labMaininfos.forEach(maininfo -> {
                addFeeList.forEach(fee -> {
                    if (maininfo.getSampleNo().equals(fee.getSampleNo()) && maininfo.getSampleda().equals(fee.getSampleda()) && maininfo.getRptGroup().equals(fee.getRptGroup())) {
                        maininfo.setAddFee(0);
                    }
                });
            });
        }
        if (CollectionUtils.isNotEmpty(errorList)) {
            labMaininfos.forEach(maininfo -> {
                errorList.forEach(fee -> {
                    if (maininfo.getSampleNo().equals(fee.getSampleNo()) && maininfo.getSampleda().equals(fee.getSampleda()) && maininfo.getRptGroup().equals(fee.getRptGroup())) {
                        maininfo.setAddFee(2);
                    }
                });
            });
        }

        return Result.succ(1, "查询成功", labMaininfos);
    }


    /**
     * LabMainInfo排序处理
     *
     * @param maininfos 待排序检验记录
     */
    public void sortLabMainInfo(List<LabMaininfo> maininfos) {
        for (LabMaininfo item : maininfos) {
            try {
                if (!BeanUtil.isEmpty(item.getSampleNo())) {
                    String a = item.getSampleNo();
                    for (Map.Entry<String, Integer> m : SortMappers.SORT_CONSTANT_MAP.entrySet()) {
                        if (item.getSampleNo().contains(m.getKey())) {
                            a = a.replace(m.getKey(), m.getValue().toString());
                        }
                    }
                    item.setSeqNo(StringUtils.isEmpty(a) ? 999999999 : Integer.parseInt(a));
                }
            } catch (NumberFormatException e) {
                item.setSeqNo(999999999);
            }
        }
    }

    public Integer replaceLetter(String keyValue) {
        Integer k = -1;
        try {
            for (Map.Entry<String, Integer> m : SortMappers.SORT_CONSTANT_MAP.entrySet()) {
                if (keyValue.contains(m.getKey())) {
                    keyValue = keyValue.replace(m.getKey(), m.getValue().toString());
                }
            }
            k = Integer.parseInt(keyValue);
        } catch (Exception exception) {
            k = 999999999;
        }
        return k;
    }


    public List<String> getSampleNoList(SampleNoRange range){
        String start = range.getS();
        String end = range.getE();
        String datePart = start.substring(0, 6);
        int startNum = Integer.parseInt(start.substring(6));
        int endNum = Integer.parseInt(end.substring(6));

        List<String> numberList = new ArrayList<>();
        for (int i = startNum; i <= endNum; i++) {
            String number = String.format("%s%04d", datePart, i);
            numberList.add(number);
        }
        return numberList;
    }

    public int getBacResultCheck(LabMaininfo labMaininfo){
        //查看 这条记录的方案是否有细菌鉴定
        LambdaQueryWrapper<BacTestWorkFlowNode> queryFlowNodeWrapper = new LambdaQueryWrapper<>();
        queryFlowNodeWrapper.eq(BacTestWorkFlowNode::getRptGroup, labMaininfo.getRptGroup())
                .eq(BacTestWorkFlowNode::getSampleda, labMaininfo.getSampleda())
                .eq(BacTestWorkFlowNode::getSampleNo, labMaininfo.getSampleNo())
                .eq(BacTestWorkFlowNode::getDelFlag,0);
        List<BacTestWorkFlowNode> flowNodeList = bacTestWorkFlowNodeMapper.selectList(queryFlowNodeWrapper);
        //查看flowNodeList中的nodeNo中是否有JINGJIAN的节点
        long cntJd = flowNodeList.stream().filter(flowNode -> flowNode.getNodeNo().equals("JINGJIAN")).count();
        if (cntJd > 0){
            //如果有鉴定则需要查看细菌结果是否有结果，如果没有结果则禁止审核
            LambdaQueryWrapper<BacTestResult> lambdaQueryWrapper3 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper3.eq(BacTestResult::getRptGroup, labMaininfo.getRptGroup())
                    .eq(BacTestResult::getSampleda, labMaininfo.getSampleda())
                    .eq(BacTestResult::getSampleNo, labMaininfo.getSampleNo())
                    .eq(BacTestResult::getDelFlag,0);
            int cntRpt = bacTestResultService.count(lambdaQueryWrapper3);
            //如果没有细菌结果则返回0
            if (cntRpt == 0){
                return 0;
            }else{
                //如果有细菌结果则需要查看细菌下得药敏结果是否有空值，有空值时不允许审核
                //BAC_DRUG_RESULT
                int j = 1;
                LambdaQueryWrapper<BacDrugTestResult> lambdaQueryWrapperd = new LambdaQueryWrapper<>();
                lambdaQueryWrapperd.eq(BacDrugTestResult::getRptGroup, labMaininfo.getRptGroup())
                        .eq(BacDrugTestResult::getSampleda, labMaininfo.getSampleda())
                        .eq(BacDrugTestResult::getSampleNo, labMaininfo.getSampleNo())
                        .eq(BacDrugTestResult::getDelFlag,0);
                List<BacDrugTestResult> bacDrugTestResultList = bacDrugTestResultService.list(lambdaQueryWrapperd);
                if(ToolsUtils.isNotEmpty(bacDrugTestResultList)){
                    for (BacDrugTestResult bacDrugTestResult : bacDrugTestResultList) {
                        if (ToolsUtils.isEmpty(bacDrugTestResult.getTestResult())){
                            j = 0;
                            break;
                        }
                    }
                }
                return j;
            }
        }else {
            //如果没有细菌鉴定节点 则需要查看其他节点下的是否有结果，如果没有则禁止审核
            int i = 0;
            LambdaQueryWrapper<BacBloodCultrue> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BacBloodCultrue::getRptGroup, labMaininfo.getRptGroup())
                    .eq(BacBloodCultrue::getSampleda, labMaininfo.getSampleda())
                    .eq(BacBloodCultrue::getSampleNo, labMaininfo.getSampleNo())
                    .eq(BacBloodCultrue::getDelFlag,0);
            if (CollectionUtils.isNotEmpty(bacBloodCultrueService.list(lambdaQueryWrapper))){
                i = 1;
            }
            LambdaQueryWrapper<BacObserResult> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper1.eq(BacObserResult::getRptGroup, labMaininfo.getRptGroup())
                    .eq(BacObserResult::getSampleda, labMaininfo.getSampleda())
                    .eq(BacObserResult::getSampleNo, labMaininfo.getSampleNo())
                    .eq(BacObserResult::getDelFlag,0);
            if (CollectionUtils.isNotEmpty(bacObserResultService.list(lambdaQueryWrapper1))){
                i = 1;
            }
            LambdaQueryWrapper<BacStainingResult> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(BacStainingResult::getRptGroup, labMaininfo.getRptGroup())
                    .eq(BacStainingResult::getSampleda, labMaininfo.getSampleda())
                    .eq(BacStainingResult::getSampleNo, labMaininfo.getSampleNo())
                    .eq(BacStainingResult::getDelFlag,0);
            if (CollectionUtils.isNotEmpty(bacStainingResultService.list(lambdaQueryWrapper2))){
                i = 1;
            }

            return i;

        }


    }

}
